//
//  HRAnswerListViewController.m
//  Hear
//
//  Created by mac on 2018/2/3.
//  Copyright © 2018年 mac. All rights reserved.
// 留声机

#import "HRCicleAnswerListViewController.h"

#import "HRFollowDynamicViewModel.h"
#import "MJRefresh.h"
#import "HRFollowDynamicCell.h"
#import "HRFollowDynamicLayout.h"
#import "HRFollowDyanmicInfoViewController.h"
#import "HRGetLikesModel.h"
#import "HRDynamicViewController.h"
#import "HRVideoPlayerCell.h"
//#import "UIView+WebVideoCache.h"
//#import "UITableView+VideoPlay.h"
//#import "MyPlayTool.h"
#import "HRDynamicBannerHeadView.h"
#import "HRDynamicBannerModel.h"
#import "PopMenu.h"
#import "HRPostDynamicViewController.h"
#import "HRRecordAudioViewController.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "HRBannerCell.h"
#import "HRAnswerBannerViewController.h"
#import "HRMainRootModel.h"
@interface HRCicleAnswerListViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property (nonatomic, strong)HRFollowDynamicViewModel *viewModel;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *contentArray;
@property (nonatomic, assign)NSInteger pIndex;
@property (nonatomic, strong)HRGetLikesModel *likesModel;
@property (nonatomic, strong)HRDynamicModel *lastDynamicModel;

@property(nonatomic, assign)CGFloat offsetY_last;
@property(nonatomic, strong, nonnull)UIView *tableViewRange;
@property (nonatomic, assign)CGFloat tempOffset;
@property(nonatomic, strong)HRDynamicBannerHeadView *bannerHeadView;
@property (nonatomic, strong)PopMenu *popMenu;

@end

@implementation HRCicleAnswerListViewController
#pragma mark - Get and Set
- (HRDynamicBannerHeadView *)bannerHeadView{
    if (_bannerHeadView == nil) {
        _bannerHeadView = [[HRDynamicBannerHeadView alloc] initWithFrame:CGRectMake(0, 0, kFullWidth, 105)];
    }
    return _bannerHeadView;
}



-(HRGetLikesModel *)likesModel{
    if (_likesModel == nil){
        _likesModel = [HRGetLikesModel new];
    }
    return _likesModel;
}
-(HRFollowDynamicViewModel *)viewModel{
    if (_viewModel == nil){
        _viewModel = [HRFollowDynamicViewModel new];
    }
    return _viewModel;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.contentArray = [NSMutableArray array];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.height -= kTabBarHeight+kNavBarHeight;

    
    
    [self getFollowDynamicList];
    
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    // Do any additional setup after loading the view.
}


- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无动态"];
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView
{
    return NO;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    self.lastDynamicModel.isPlaying = NO;
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stopPlayVoiceNotification" object:nil];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.contentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HRFollowDynamicLayout *layout = self.contentArray[indexPath.row];
    WeakSelf
    if ([layout.dynamicModel.MomentType intValue] != 6){
        HRFollowDynamicCell *cell = [HRFollowDynamicCell cellWithTableView:tableView];
        if (layout)
        {
            cell.layout = layout;
        }
        
        cell.playMedioBlock = ^(HRDynamicModel *currentDynamicModel){
            if (currentDynamicModel || self.lastDynamicModel){
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(![currentDynamicModel.LocalId isEqualToString:self.lastDynamicModel.LocalId]){
                        weakSelf.lastDynamicModel.isPlaying = NO;
                    }
                    [weakSelf.tableView reloadData];
                    weakSelf.lastDynamicModel = currentDynamicModel;
                });
            }
        };
        cell.likeButtonClickBlock = ^(BOOL isLike){
            [weakSelf getDynamicLike:isLike andDynamic:layout.dynamicModel andFromIndex:indexPath.row];
        };
        cell.clickIconBlock = ^(){
            if ([layout.dynamicModel.UserLocalId isEqualToString:USERID]) return ;
            HRDynamicViewController *dynamicVC = [HRDynamicViewController new];
            dynamicVC.currentUserID = layout.dynamicModel.UserLocalId;
            //            dynamicVC.hidesBottomBarWhenPushed = YES;
            
            [weakSelf.navigationController pushViewController:dynamicVC animated:YES];
        };
        // 点击标签
        cell.tagButtonSenderBlock = ^(){
//            HRFollowDynamicViewController *dynamicVC = [HRFollowDynamicViewController new];
//            dynamicVC.MomentTagCode = layout.dynamicModel.MomentTagCode;
//            dynamicVC.dynamicType = TagListDynaimc;
//            dynamicVC.MomentTagName = layout.dynamicModel.MomentTagName;
//            [weakSelf.navigationController pushViewController:dynamicVC animated:YES];
        };
        
        cell.showMoreContentButtonBlock = ^(){// 展开
            layout.isShowRealyCellHeight = !layout.isShowRealyCellHeight;
            layout.dynamicModel = layout.dynamicModel;
            [weakSelf.tableView reloadRow:indexPath.row inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        };
        //取消cell的点击状态
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else if ([layout.dynamicModel.MomentType intValue] == 6){
        HRBannerCell *cell = [HRBannerCell cellWithTableView:tableView];
        cell.layout = layout;
        cell.answerButtonBlock = ^{
            HRAnswerBannerViewController *VC = [HRAnswerBannerViewController new];
            [weakSelf.navigationController pushViewController:VC animated:YES];
        };
        return cell;
    }
    return nil;
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HRFollowDynamicLayout *layout = self.contentArray[indexPath.row];
    if ([layout.dynamicModel.MomentType intValue] == 6){
        return 420;
    }else{
        return layout.cellHeight;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HRFollowDynamicLayout *layout = self.contentArray[indexPath.row];
    if ([layout.dynamicModel.IsRecommend intValue] ==1){
        [MobClick event:@"Hearer11"];
    }
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([layout.dynamicModel.MomentType intValue] == 6){
        return;
    }
    HRFollowDyanmicInfoViewController *infoVC = [HRFollowDyanmicInfoViewController new];
    HRFollowDynamicLayout *detailLayout = [HRFollowDynamicLayout new];
    detailLayout.style = HRFollowLayoutStyleDetail;
    detailLayout.dynamicModel = layout.dynamicModel;
    infoVC.layout = detailLayout;
    //    infoVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:infoVC animated:YES];
    WeakSelf
    infoVC.reloadListBlock = ^(NSMutableArray *commentArr){
        if (commentArr.count){
            HRDynamicModel *dynaModel = layout.dynamicModel;
            dynaModel.comentListArray = commentArr;
            layout.dynamicModel = dynaModel;
        }
        [weakSelf.tableView reloadRow:indexPath.row inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    };
}

/**
 * Called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
 * 松手时已经静止, 只会调用scrollViewDidEndDragging
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    //if (decelerate == NO)
    // scrollView已经完全静止
    
    //   [self showTabBar];
    //        [self.tableView handleScrollStop];
}

/**
 * Called on tableView is static after finger up if the user dragged and tableView is scrolling.
 * 松手时还在运动, 先调用scrollViewDidEndDragging, 再调用scrollViewDidEndDecelerating
 */
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//
//    // scrollView已经完全静止
//    [self.tableView handleScrollStop];
//}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//
//    // 处理滚动方向
//    [self handleScrollDerectionWithOffset:scrollView.contentOffset.y];
//
//    // Handle cyclic utilization
//    // 处理循环利用
//    [self.tableView handleQuickScroll];
//}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //    if (self.dynamicType != TagListDynaimc){
    //        if (self.tempOffset > scrollView.contentOffset.y){
    //            if (self.tabBarController.tabBar.isHidden){
    //                [self showTabBar];
    //            }
    //        }
    //        self.tempOffset = scrollView.contentOffset.y;
    //    }
    
}

- (void)hideTabBar{
    WeakSelf
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tabFrame = self.tabBarController.tabBar.frame;
        tabFrame.origin.y = [[UIScreen mainScreen] bounds].size.height;
        self.tabBarController.tabBar.frame = tabFrame;
    } completion:^(BOOL finished) {
        weakSelf.tabBarController.tabBar.hidden = YES;;
    }];
    
}

- (void)showTabBar{
    WeakSelf
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tabFrame = self.tabBarController.tabBar.frame;
        tabFrame.origin.y = kFullHeight-49;
        self.tabBarController.tabBar.frame = tabFrame;
    } completion:^(BOOL finished) {
        weakSelf.tabBarController.tabBar.hidden = NO;
        
        //        DDLog(@"11111111111111111=======offset======%f tempOffset=======%f",offset,self.tempOffset);
        
    }];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //    if(_dynamicType != TagListDynaimc){
    //        [self hideTabBar];
    //    }
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //    if(_dynamicType != TagListDynaimc){
    //        [self showTabBar];
    //    }
}



//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    self.offsetY_last = scrollView.contentOffset.y;
//}

//-(void)handleScrollDerectionWithOffset:(CGFloat)offsetY{
//    self.tableView.currentDerection = (offsetY-self.offsetY_last>0) ? JPVideoPlayerDemoScrollDerectionUp : JPVideoPlayerDemoScrollDerectionDown;
//    self.offsetY_last = offsetY;
//}



- (void)getFollowDynamicList{
    self.pIndex = 0;
    [self getFollowDynamic:YES];
    
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pIndex = 0;
        [self getFollowDynamic:YES];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
    //    //上拉加载
    self.tableView.mj_footer=[MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.pIndex ++;
        [weakSelf getFollowDynamic:NO];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    
}

- (void)getFollowDynamic:(BOOL)isHead{
    HRMainRootRequestModel *requestModel = [HRMainRootRequestModel new];
    requestModel.PageSize = @"15";
    requestModel.PageIndex = self.pIndex;
    requestModel.CurrentUserLocalId = USERID;
    requestModel.Sex = 2;
    requestModel.SortType = 0;
    requestModel.StartAge = @"18";
    requestModel.EndAge = @"50";
    requestModel.QuestionPageIndex = @"0";
    requestModel.QuestionPageSize = @"0";
    requestModel.QuestionID = @"0";
    requestModel.ParentQuestionID = @"0";
    
    
    WeakSelf
    [self.viewModel getDynamicAnswerList:requestModel andUrl:@"SoundInfo/Get_GetSoundMoments" resultArray:^(NSArray *resultArr) {
        if (resultArr){
            if (isHead){
                [weakSelf.contentArray removeAllObjects];
            }
            [weakSelf.contentArray addObjectsFromArray:resultArr];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                
                if (weakSelf.contentArray.count < 10){
                    weakSelf.tableView.mj_footer.hidden = YES;
                }else{
                    weakSelf.tableView.mj_footer.hidden = NO;
                }
                
            });
        }
    }];
}

#pragma 点赞
- (void)getDynamicLike:(BOOL)isLike andDynamic:(HRDynamicModel *)dynamicModel andFromIndex:(NSUInteger)index{
    
    WeakSelf
    
    if (isLike){
        [weakSelf.likesModel getLikeRequest:@{@"MomentLocalId":dynamicModel.LocalId,@"LocalId":dynamicModel.LocalId,@"UserLocalId":USERID,@"CreateTime":[self getCurrentTime]} isSeccess:^(BOOL isSeccess) {
            if(isSeccess){
                dynamicModel.LikeCount = dynamicModel.LikeCount+1;
                dynamicModel.IsLike = @"1";
                //                [weakSelf.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
        //        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
        //
        //        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        //
        //        });
        
    }else{
        [weakSelf.likesModel getDeletLikeRequest:@{@"MomentLocalId":dynamicModel.LocalId,@"UserLocalId":USERID} isSeccess:^(BOOL isSeccess) {
            if (isSeccess){
                if (dynamicModel.LikeCount){
                    dynamicModel.LikeCount = dynamicModel.LikeCount-1;
                }
                dynamicModel.IsLike = @"0";
                //                [weakSelf.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationNone];
                
            }
        }];
        //        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
        //
        //        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        //
        //        });
    }
}
- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

-(void)insertLineInScreenCenter{
    [[UIApplication sharedApplication].keyWindow insertSubview:self.tableViewRange aboveSubview:self.tableView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
